package vn.edu.saigontech.ncms.service.impl;

import java.util.Collection;
import java.util.Date;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.system.USD;
import vn.edu.saigontech.ncms.service.USDService;
import vn.edu.saigontech.ncms.util.DateUtil;

public class USDServiceImpl extends HibernateGenericService<USD, Long> implements USDService {

	@Override
	public USD findByDate(Date date) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("date", date));
		return (USD) criteria.uniqueResult();
	}

	@Override
	public USD findCurrent() {
		USD now = this.findByDate(DateUtil.newDate());
		if(now == null) {
			Criteria criteria = this.createCriteria();
			criteria.addOrder(Order.desc("date"));
			criteria.setMaxResults(1);
			return (USD) criteria.uniqueResult();
		}
		return now;
	}

	@SuppressWarnings("unchecked")
	public Collection<USD> findByMonth(Integer month, Integer year) {
		Date startDate = DateUtil.getStartDateOfMonth(month, year);
		Date endDate = DateUtil.getEndDateOfMonth(month, year);
		
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.between("date", startDate, endDate));
		return criteria.list();
	}
}